package com.pipi.controller;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.pipi.dao.pojo.OrderMain;
import com.pipi.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.pipi.constant.OrderConstant;
import com.pipi.dao.pojo.OrderItem;
import com.pipi.service.OrdeMainService;
import com.pipi.service.OrderItemService;
import com.pipi.utils.PIPIUtils;
import com.pipi.utils.sql.Query;

@RestController
@RequestMapping("/order")
public class OrderController {

	@Autowired
	private OrdeMainService orderMainService;

	@Autowired
	private OrderItemService orderItemService;

	/**
	 * 生成订单
	 * 
	 * @param openid
	 * @param totalMoney
	 * @param remarks
	 * @return
	 */
	@RequestMapping("/saveOrder")
	public Result saveOrder(String openid, String totalMoney, String remarks, Integer selectedAddrId) {
		String orderId = orderMainService.saveOrder(openid, totalMoney, remarks, selectedAddrId);
		return Result.ok(orderId);
	}

	@RequestMapping("/changeStatus")
	public Result changeStatus(String orderId, Integer flag) {
		orderMainService.changeStatus(orderId, flag);
		return Result.ok();
	}

	/**
	 * 得到openID用户的所有订单
	 * 
	 * @param openid
	 * @return
	 */
	@RequestMapping("/getAllOrder")
	public Result getAllOrderSample(String openid) {
		List<OrderSample> list = orderMainService.getAllOrderSample(openid);
		return Result.ok(list);
	}

	/**
	 * 根据订单id得到订单详情
	 * 
	 * @param orderId
	 * @return
	 */
	@RequestMapping("/getOrderDetailByOrderId")
	public Result getOrderDetailByOrderId(String orderId) {
		OrderDetail detail = orderMainService.getOrderDetailByOrderId(orderId);
		return Result.ok(detail);
	}

	/**
	 * 商家获取所有订单
	 * 
	 * @return
	 */
	@RequestMapping("/getOrders")
	public Map<String, Object> getOrders(@RequestParam(defaultValue = "1") Integer page,
			@RequestParam(defaultValue = "10") Integer rows, @RequestParam(defaultValue = "0") Integer status) {
		Map<String, Object> map = orderMainService.getOrders(page, rows, status);
		return map;
	}

	/**
	 * 根据orderId得到菜单商品列表
	 */
	@RequestMapping("/getDisksByOrderId")
	public Result getDisksByOrderId(String orderId) {
		List<OrderItem> list = orderItemService.getOrderItemByOrderId(orderId);
		return Result.ok(list);
	}

	/**
	 * 获取订单统计信息（包含取消订单和完成订单的数据汇总）
	 *
	 * @param params 查询参数集合，需要包含时间范围等必要查询条件，方法内部会动态修改status字段值
	 * @return Result 统一返回结果，data属性包含cancel（取消订单）和complete（完成订单）的统计对象
	 * @throws ParseException 当日期参数解析异常时抛出
	 */
	@RequestMapping("/getStatistics")
	public Result getStatistics(Map<String, Object> params,String startDate,String endDate) throws ParseException {
		if (!(startDate == null|| startDate.isEmpty())){
			params.put("startDate", startDate);
		}
		if (!(endDate == null|| endDate.isEmpty())){
			params.put("endDate", endDate);
		}

		/* 查询未付款取消订单的统计数据 */
		params.put("status", OrderConstant.CANCEL_NO_PAY);
		System.out.println("未付款取消："+params);
		Statistics CANCEL_NO_PAY = orderMainService.getStatistics(new Query(params));

		/* 查询已付款后取消订单的统计数据 */
		params.put("status", OrderConstant.CANCEL_PAY);
		System.out.println("付款取消"+params);
		Statistics CANCEL_PAY = orderMainService.getStatistics(new Query(params));

		/* 合并两类取消订单数据：数量相加，金额相加并格式化 */
		Statistics cancel = new Statistics();
		cancel.setSum(CANCEL_NO_PAY.getSum() + CANCEL_PAY.getSum());
		// 处理空值情况并计算总金额
		double c1 = Double.parseDouble(CANCEL_NO_PAY.getTotal() == null ? "0" : CANCEL_NO_PAY.getTotal());
		double c2 = Double.parseDouble(CANCEL_PAY.getTotal() == null ? "0" : CANCEL_PAY.getTotal());
		cancel.setTotal(PIPIUtils.formatMoney(String.valueOf(c1 + c2)));

		/* 获取完成订单的统计数据并格式化金额字段 */
		params.put("status", OrderConstant.COMPLETE);
		System.out.println("完成订单："+params);
		Statistics complete = orderMainService.getStatistics(new Query(params));
		// 处理空值情况并计算总金额
		complete.setTotal(complete.getTotal() == null ? "0" : PIPIUtils.formatMoney(complete.getTotal()));

		/* 构建结果集合并返回 */
		Map<String, Statistics> map = new HashMap<String, Statistics>();
		map.put("cancel", cancel);
		map.put("complete", complete);

		return Result.ok(map);
	}

	/**
	 * 护理（配送）人员获取所有订单
	 */
	@RequestMapping("/getAllOrders")
	public Result getAllOrders(String openID) {
		List<Order> list = orderMainService.getAllOrdersSample(openID);
		return Result.ok(list);
	}

	/**
	 * 护理人员接取订单
	 */
	@RequestMapping("/acceptOrder")
	public Result acceptOrder(String orderId, String openID) {
		orderMainService.updateOrderHlry(orderId, openID);
		return Result.ok();
	}

	/**
	 * 护理人员配送订单
	 */
	@RequestMapping("/deliverOrder")
	public Result deliverOrder(String orderId) {
		List address = orderMainService.getOrderAddressByOrderId(orderId);
		return Result.ok(address);
	}

	/**
	 * 护理人员完成订单
	 */
	@RequestMapping("/completeOrder")
	public Result completeOrder(String orderId) {
		orderMainService.updatecompleteOrder(orderId);
		return Result.ok();
	}

}
